// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Y [author] rhyme_lph
// F [email]  rhymelph@gmail.com
// d [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/invite_member_entity.dart';
import 'package:finance_app/src/page/dashboard/contact/employee_contacts_page.dart';
import 'package:finance_app/src/provider/invite_team/assign_role_by_batch_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/select/employee_item_radio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "assignRoleByBatchPage")
class AssignRoleByBatchPage extends StatefulWidget {
  const AssignRoleByBatchPage({Key key}) : super(key: key);

  @override
  _AssignRoleByBatchPageState createState() => _AssignRoleByBatchPageState();
}

class _AssignRoleByBatchPageState extends State<AssignRoleByBatchPage>
    with PagePresenter<AssignRoleByBatchPage, AssignRoleByBatchProvider> {
  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.assign_role_by_batch, actions: [
        NormalNextTextButton(
          onTap: provider.onNext,
        ),
      ]);

  @override
  void initState() {
    super.initState();
  }

  @override
  // TODO: implement buildEmptyWidget
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<String>(
                    selector: (_, __) => __.searchController.text,
                    builder:
                        (BuildContext context, String value, Widget child) =>
                            CustomScrollView(
                      slivers: buildSearchWidget(value),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      );

  List<Widget> buildSearchWidget(String value) {
    List<Widget> slivers;
    // if (provider.searchController.text.isNotEmpty) {
    slivers = provider.searchData.entries
        .toList()
        .where(_onSearchInputGroup)
        .map((e) => buildSliver(e.key, _onSearchInputItem(e.value)))
        .toList();
    // } else {
    //   slivers = provider.searchData.entries
    //       .toList()
    //       .map((e) => buildSliver(e.key, e.value))
    //       .toList();
    // }

    return slivers;
  }

  Widget buildSliver(String title, List<InviteMemberEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<InviteMemberEntity> data, int i) {
    InviteMemberEntity lastItemInList = provider.searchData.entries
        .toList()
        .where(_onSearchInputGroup)
        .map((e) => _onSearchInputItem(e.value))
        .toList()
        .last
        .last;

    return listBuilder<Tuple2<InviteMemberEntity, bool>>(
      selector: (_, __) => Tuple2(
          data[i],
          __.currentSelectList.firstWhere((element) => element.id == data[i].id,
                  orElse: () => null) !=
              null),
      builder: (BuildContext context, Tuple2<InviteMemberEntity, bool> value,
              Widget child) =>
          Column(
        children: [
          PressedOpacityButton(
            onPressed: () => provider.onSelectDetail(value.item1),
            child: EmployeeItemCheckBox(
              title: value.item1.name,
              isSelect: value.item2,
              isEnable: true,
              isShowTitle: false,
              isLastItem: data.length == i + 1,
            ),
          ),
          if (lastItemInList == value.item1) AppSpaces.h85(context),
        ],
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }

  bool _onSearchInputGroup(MapEntry<String, List<InviteMemberEntity>> element) {
    return _onSearchInputItem(element.value).length > 0;
  }

  List<InviteMemberEntity> _onSearchInputItem(
      List<InviteMemberEntity> element) {
    String searchInput = provider.searchController.text;
    List<InviteMemberEntity> data = [];
    for (final item in element) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.name)) {
        data.add(item);
      }
    }
    return data;
  }
}
